from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from stock_spider.pipelines import StockTable

# MySQL密码
MYSQL_PASSWORD = "123456"  # 将这里替换为实际密码

def query_stocks():
    """查询并显示股票数据"""
    try:
        # 连接数据库
        engine = create_engine(f'mysql+pymysql://root:{MYSQL_PASSWORD}@localhost:3306/stock_db?charset=utf8mb4')
        # ... 其余代码不变
        Session = sessionmaker(bind=engine)
        session = Session()
        
        # 查询所有股票
        stocks = session.query(StockTable).order_by(StockTable.id).all()
        
        print("\n" + "="*120)
        print(f"{'序号':<4} {'股票代码':<10} {'股票名称':<10} {'最新价':<8} {'涨跌幅%':<8} {'成交量':<12} {'最高':<8} {'最低':<8} {'更新时间':<20}")
        print("="*120)
        
        for stock in stocks:
            print(f"{stock.id:<4} {stock.stock_code:<10} {stock.stock_name:<10} "
                  f"{stock.latest_price:<8.2f} {stock.change_percent:<8.2f} "
                  f"{stock.volume:<12} {stock.high:<8.2f} {stock.low:<8.2f} {stock.timestamp:<20}")
        
        print(f"\n总共查询到 {len(stocks)} 条股票记录")
        
    except Exception as e:
        print(f"查询数据时出错: {e}")
        print("请确保数据库已创建并且有数据")
    finally:
        session.close()

if __name__ == '__main__':
    query_stocks()